package com.xjl.app.controller;

import com.alibaba.druid.sql.ast.SQLPartitionValue;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.xjl.app.EntityDTO.DevicesCallBackMessageDTO;
import com.xjl.app.infra.entity.DevicesCallBackMessage;
import com.xjl.app.infra.enums.AlarmTypeEnum;
import com.xjl.app.infra.service.DevicesCallBackMessageService;
import com.xjl.app.mq.sender.AiAlarmTestSender;
import com.xjl.app.service.DeviceCallBackMessageDTOService;
import com.xjl.common.redis.utils.StringRedisTemplateProxy;
import com.xjl.common.web.Res.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import com.xjl.tools.AtomicQueue;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("alarm/message")
@RequiredArgsConstructor
public class DeviceCallBackMessageDTOController {

    private final DeviceCallBackMessageDTOService deviceCallBackMessageDTOService;
    private final DevicesCallBackMessageService devicesCallBackMessageService;
    private AtomicQueue<DevicesCallBackMessageDTO> atomicQeue = new AtomicQueue<>(1<<5);

    private final StringRedisTemplate stringRedisTemplate;
    @Value("${redisKey.app.message:}")
    private String messageCachekey;

    @PostMapping("callback")
    public Result callback(MultipartFile img ){
        DevicesCallBackMessageDTO messageDTO = DevicesCallBackMessageDTO.builder()
                        .alarmType(AlarmTypeEnum.ELSE_ALARM.getAlarmType())
                        .deviceId(44313212)
                        .picture((String) upload(img).getData())
                        .stationId(String.valueOf(12412321))
                        .build();
        DevicesCallBackMessage save = deviceCallBackMessageDTOService.save(messageDTO);
        if(save==null){
            log.error(" 保存设备回调失败! ");
            return Result.error();
        }
        String jsonString = JSON.toJSONString(save);
        Long callBackId = save.getCallBackId();
        messageDTO.setCallBackId(callBackId);
        boolean res = deviceCallBackMessageDTOService.callback(messageDTO);
        if(!res){
            return Result.error(jsonString);
        }
        return Result.ok(jsonString);
    }

    //降级策略: 消息未发送成功,或者mq nameserver宕机,定时获取消息缓存,手动发送消息
    @GetMapping("get/messageCache")
    public Result getMessageCache(){
        String key = messageCachekey+"*";
        Set<String> keys = stringRedisTemplate.keys(key);
        List<String> strings = stringRedisTemplate.opsForValue().multiGet(keys);
        return Result.ok(strings);
    }

    public Result upload(MultipartFile img) {
        if (img.isEmpty()) {
            return Result.error("未选择图片", HttpStatus.BAD_REQUEST);
        }
        try {
            String imgPath = "iot-application/app-starter/src/main/resources/static/images/";
            File directory = new File(imgPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            String fileName = UUID.randomUUID().toString() + "_" + img.getOriginalFilename();
            File destFile = new File(directory, fileName);
            FileCopyUtils.copy(img.getBytes(), destFile);
            return Result.ok(fileName);
        } catch (IOException e) {
            return Result.error("上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
